<?php

namespace app\index\service;

use app\admin\service\PersonnelService;
use app\common\model\Member;
use app\common\model\UserPersonnel;
use app\index\dao\UserPersonnelDao;
use app\index\model\UM as UM;
use ShidianUtil\Exception\DataNotExistException;

/**
 * Class PersonnelBindService
 * @package app\index\service
 */
class PersonnelBindService
{
    // dao
    private UserPersonnelDao $userPersonnelDao;

    public function __construct(UserPersonnelDao $userPersonnelDao)
    {
        $this->userPersonnelDao = $userPersonnelDao;
    }

    /**
     * 更新
     * @param UM $user
     * @param int $id
     * @param array $params
     * @return void
     */
    public function modify(UM $user, int $id, array $params): void
    {
        $record = UserPersonnel::field(true)
            ->where('id', $id)
            ->with(['member'])
            ->find();

        if (is_null($record)) {
            throw new DataNotExistException('该邀请不存在或已被删除');
        }

        $this->bind($user, $record);
    }

    public function bindNotLogin($id, array $params): void
    {

        $record = UserPersonnel::field(true)
            ->where('id', $id)
            ->with(['member'])
            ->find();

        if (is_null($record)) {
            throw new DataNotExistException('该邀请不存在或已被删除');
        }

        $member = Member::where('phone', $record->mobile)->whereIn('status', [0, 1])->find();
        if (is_null($member)) {
            throw new DataNotExistException('该用户不存在或已被删除');
        }

        $this->bind($member, $record);
    }

    private function bind(Member $member, UserPersonnel $userPersonnel)
    {
        $this->getPersonnelService()->bindMemberAndPersonnel($member, $userPersonnel);
    }

    private function getPersonnelService(): PersonnelService
    {
        return app(PersonnelService::class);
    }
}
